//
//  JpToast.m
//
//  Created by apple on 15/6/14.
//  Copyright (c) 2015年 wangjinping. All rights reserved.
//

#import "JPToast.h"
#import <libkern/OSAtomic.h>

@interface JPToast( ){
    UIButton *_tipsBt;
    UILabel *_tipLb;
}

@property(nonatomic, assign) BOOL isEnabled;
@property(nonatomic, assign) BOOL isDebugEnabled;

@end


@implementation JPToast

void showText(NSString *text) {
    [JPToast showText:text];
}

void debugText(NSString *text) {
    [JPToast debugText:text];
}

//JPToast单例
+ (JPToast *)sharedToast {
    static JPToast *toast = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        toast = [[self alloc] init];
        toast.isEnabled = YES;
    });
    return toast;
}

//使能是否弹出toast
+(void) setShowEnabled:(BOOL)isEnabled {
    JPToast *toast = [JPToast sharedToast];
    toast.isEnabled = isEnabled;
}

+(void) setDebugEnabled:(BOOL)isDebugEnabled {
    JPToast *toast = [JPToast sharedToast];
    toast.isDebugEnabled = isDebugEnabled;
}

//弹出toast
+(void) showText:(NSString *) text {
    JPToast *toast = [JPToast sharedToast];
    if (!toast.isEnabled) return;
    toast.alpha = 1;
    [toast updateTips:text];
    [[UIApplication sharedApplication].keyWindow addSubview:toast];
}

//弹出toast
+(void) debugText:(NSString *) text {
    JPToast *toast = [JPToast sharedToast];
    if (!toast.isEnabled) return;
    if (!toast.isDebugEnabled) return;
    toast.alpha = 1;
    [toast updateTips:text];
    [[UIApplication sharedApplication].keyWindow addSubview:toast];
}

//初始化工作
- (id) initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _tipsBt = [[UIButton alloc] init];
        _tipLb = [[UILabel alloc] init];
        [self addSubview:_tipsBt];
        [_tipsBt addSubview:_tipLb];
    }
    return self;
}

//更新内容
- (void) updateTips:(NSString *) tips{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(disMiss:) object:nil];
    [self performSelector:@selector(disMiss:) withObject:nil afterDelay:2];
    
    float width = [UIScreen mainScreen].bounds.size.width;
    float height = [UIScreen mainScreen].bounds.size.height;
    float margin = 10;
    CGSize size =  [self getFontSize:14 withText:tips withWidth:width-100];
    CGRect rect = CGRectMake(width/2-(size.width+margin+margin)/2, height-110, size.width+margin+margin, size.height+margin+margin/2);
    
    [_tipLb setFrame:CGRectMake(0, 0, rect.size.width, rect.size.height)];
    [_tipLb setText:tips];
    [_tipLb setBackgroundColor:[UIColor clearColor]];
    [_tipLb setTextColor:[UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1]];
    [_tipLb setFont:[UIFont systemFontOfSize:14]];
    [_tipLb setTextAlignment:NSTextAlignmentCenter];
    [_tipLb setNumberOfLines:0];
    
    UIColor *scolor = [UIColor colorWithRed:62/255.0 green:62/255.0 blue:62/255.0 alpha:1];
    UIColor *ecolor = [UIColor colorWithRed:45/255.0 green:45/255.0 blue:45/255.0 alpha:1];
    UIImage *image = [self createImageWithColors:[NSArray arrayWithObjects:(id)scolor,(id)ecolor, nil] withSize:rect.size];
    image = [self clipImageWithCornerRadius:5 image:image];
    [_tipsBt setFrame:rect];
    [_tipsBt setBackgroundImage:image forState:UIControlStateNormal];
    [_tipsBt imageView].layer.cornerRadius = 5;
    [_tipsBt imageView].layer.masksToBounds = YES;
    [_tipsBt setBackgroundColor:[UIColor clearColor]];
    [_tipsBt.layer setCornerRadius:5];
    [_tipsBt.layer setShadowColor:[UIColor colorWithRed:33/255.0 green:33/255.0 blue:33/255.0 alpha:1].CGColor];
    [_tipsBt.layer setShadowOffset:CGSizeMake(0, 8)];//shadowOffset阴影偏移,x向右偏移4，y向下偏移4，默认(0, -3),这个跟shadowRadius配合使用
    [_tipsBt.layer setShadowOpacity:0.4f];//阴影透明度，默认0
    
    [_tipsBt.layer removeAllAnimations];
    CGRect eRect = [_tipsBt frame];
    CGRect sRect = CGRectMake(eRect.origin.x, height, eRect.size.width, eRect.size.height);
    //开始动画
    [self startAnimation:_tipsBt startRect:sRect endRect:eRect withDuration:.3 block:^{
        float height = [UIScreen mainScreen].bounds.size.height;
        CGRect eRect = [_tipsBt frame];
        CGRect sRect = CGRectMake(eRect.origin.x, height-110, eRect.size.width, eRect.size.height);
        eRect = CGRectMake(eRect.origin.x, height-100, eRect.size.width, eRect.size.height);
        [self startAnimation:_tipsBt startRect:sRect endRect:eRect withDuration:.5 block:nil];
    }];
}

//动画
- (void)startAnimation:(UIView *)view startRect:(CGRect)sRect endRect:(CGRect)eRect withDuration:(float)duration block:(void (^)(void))back{
    [view setFrame:sRect];
    [UIView animateWithDuration:duration delay:0 usingSpringWithDamping:1 initialSpringVelocity:1 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        [view setFrame:eRect];
    } completion:^(BOOL finished) {
        if (finished && back != nil) {
            back();
        }
    }];
}

//toast消失
- (void)disMiss:(id) sender {
    JPToast *toast = [JPToast sharedToast];
    [UIView animateWithDuration:0.4 animations:^{
        toast.alpha = 0;
    } completion:^(BOOL finished) {
        if (finished) {
            [toast removeFromSuperview];
        }
    }];
}

//根据字体大小获取文本的尺寸
- (CGSize) getFontSize:(int) size withText:(NSString *)text withWidth:(float) width {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_7_0  //iPhone OS SDK 3.0 以后版本的处理
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:size]};
    NSStringDrawingOptions options = (NSStringDrawingOptions) (NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin);
    CGRect rect = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT)  options:options  attributes:attributes  context:nil];
    return rect.size;
#else  //iPhone OS SDK 3.0 之前版本的处理
    return [text sizeWithFont:[UIFont systemFontOfSize:size] constrainedToSize:CGSizeMake(width, MAXFLOAT)];
#endif
}

//制作渐变图片
- (UIImage*)createImageWithColors:(NSArray*) colors withSize:(CGSize)size {
    NSMutableArray *ar = [NSMutableArray array];
    for(UIColor *c in colors) {
        [ar addObject:(id)c.CGColor];
    }
    UIGraphicsBeginImageContextWithOptions(size, YES, 1);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGColorSpaceRef colorSpace = CGColorGetColorSpace([[colors lastObject] CGColor]);
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)ar, NULL);
    CGPoint start = CGPointMake(0.0, 00);
    CGPoint end = CGPointMake(0.0, size.height);

    CGContextDrawLinearGradient(context, gradient, start, end, kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    CGGradientRelease(gradient);
    CGContextRestoreGState(context);
    CGColorSpaceRelease(colorSpace);
    UIGraphicsEndImageContext();
    
    return image;
}

//裁剪图片
- (UIImage *)clipImageWithCornerRadius:(CGFloat)cornerRadius image:(UIImage *)originImage{
    CGFloat w = originImage.size.width;
    CGFloat h = originImage.size.height;
    CGFloat scale = [UIScreen mainScreen].scale;
    // 防止圆角半径小于0，或者大于宽/高中较小值的一半。
    if (cornerRadius < 0) {
        cornerRadius = 0;
    } else if (cornerRadius > MIN(w, h)) {
        cornerRadius = MIN(w, h)/2.0;
    }
    
    UIImage *image = nil;
    CGRect imageFrame = CGRectMake(0., 0., w, h);
    UIGraphicsBeginImageContextWithOptions(originImage.size, NO, scale);
    [[UIBezierPath bezierPathWithRoundedRect:imageFrame cornerRadius:cornerRadius] addClip];
    [originImage drawInRect:imageFrame];
    image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

@end
